package flc.ast.utils;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.MediaPlayer;

import java.io.IOException;

public class AudioPlayer {

    private static AudioPlayer instance;
    private final MediaPlayer audioPlayer;

    private AudioPlayer() {
        audioPlayer = new MediaPlayer();
    }

    public synchronized static AudioPlayer getInstance() {
//        if (instance == null) {
        instance = new AudioPlayer();
//        }
        return instance;
    }

    public MediaPlayer getAudioPlayer() {
        return audioPlayer;
    }

    public void startVoice(Context context, String selectVoicePath) {
        try {
            audioPlayer.reset();
            //获得播放源访问入口
            AssetManager am = context.getAssets();
            AssetFileDescriptor afd = am.openFd(selectVoicePath);// 注意这里的区别
            //给MediaPlayer设置播放源
            audioPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
        } catch (IOException e) {
            e.printStackTrace();
        }
        //设置准备就绪状态监听
        audioPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                // 开始播放
                audioPlayer.start();
            }
        });
//        audioPlayer.setLooping(true);
        audioPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                if (listener != null) {
                    listener.playComplete(mp);
                }
            }
        });
        //准备播放
        audioPlayer.prepareAsync();
    }

    private IListener listener;

    public void setListener(IListener listener) {
        this.listener = listener;
    }

    public interface IListener {
        void playComplete(MediaPlayer mp);
    }
}
